import { loadOrgList } from '@/pages/Enterprise/Org/service';
import { loadPostSelect } from '@/pages/Enterprise/Post/service';
import ProForm, { ModalForm, ProFormRadio, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ActionType, EditableProTable, ProColumns } from '@ant-design/pro-table';
import { Button, Drawer, FormInstance, Popconfirm, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { EmployeeBody, EmployeeListItem, OrgPost } from '../List/data';
import {
  attachedCheckEmployee,
  attachedLeaveEmployee,
  loadEmployee,
  updateEmployee,
} from '../List/service';
import type { AttachedDetailItem } from './data';
import { attachedDetail, attachedList } from './service';

const AttacList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */

  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const actionRefDetail = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<EmployeeListItem>();
  const [currentRowDetail, setCurrentRowDetail] = useState<AttachedDetailItem>();
  const formRef = useRef<FormInstance>();
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>();

  const saveSubmit = async (values: EmployeeBody) => {
    try {
      await attachedCheckEmployee(values);
      actionRefDetail.current?.reload();
    } catch (e) {
      return false;
    }
    return true;
  };

  const requestOrg = async () => {
    return loadOrgList({ status: '0' }).then(({ data }) => {
      return data;
    });
  };
  const requestPost = async () => {
    return loadPostSelect().then(({ data }) => {
      return data;
    });
  };

  /** 国际化配置 */
  const columns: ProColumns<EmployeeListItem>[] = [
    {
      dataIndex: 'index',
      title: '序号',
      width: 48,
      align: 'center',
      valueType: 'index',
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRef?.current?.pageInfo?.current || 1) - 1) *
                (actionRef?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '员工姓名',
      key: 'name',
      dataIndex: 'name',
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '身份证号',
      key: 'idCard',
      dataIndex: 'idCard',
    },
    {
      title: '是否在职',
      key: 'workType',
      dataIndex: 'workType',
      render: (dom, entity, index) => {
        if (entity.workType > 0) {
          return <Tag key={'workType' + entity.workType}>是</Tag>;
        }
        return <Tag key={'workType' + entity.workType}>否</Tag>;
      },
    },
    {
      title: '加入时间',
      key: 'createTime',
      search: false,
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      key: 'option',
      valueType: 'option',
      render: (_, record) => {
        return [
          <Button
            type="link"
            size="small"
            key={record.employeeId}
            onClick={() => {
              record.flag = Date.now();
              setCurrentRow(record);
              handleModalVisible(true);
            }}
          >
            记录详情
          </Button>,
          record.workType > 0 && (
            <Popconfirm
              key="delete"
              okButtonProps={{ danger: true }}
              title={`确认解聘员工【${record.name}】?`}
              onConfirm={async () => {
                // setCurrentRow(record);
                await attachedLeaveEmployee(record.employeeId);
                actionRefDetail.current?.reloadAndRest?.();
              }}
              okText="解聘"
              cancelText="取消"
            >
              <Button danger size="small" type="link">
                解聘
              </Button>
            </Popconfirm>
          ),
        ];
      },
    },
  ];

  const detailColumns: ProColumns<AttachedDetailItem>[] = [
    {
      dataIndex: 'index',
      title: '序号',
      width: 48,
      align: 'center',
      valueType: 'index',
      fixed: true,
      render: (dom, entity, index) => {
        return (
          <span>
            {index +
              1 +
              ((actionRefDetail?.current?.pageInfo?.current || 1) - 1) *
                (actionRefDetail?.current?.pageInfo?.pageSize || 5)}
          </span>
        );
      },
    },
    {
      title: '操作',
      key: 'option',
      align: 'center',
      width: 80,
      valueType: 'option',
      fixed: true,
      render: (_, record, index) => {
        if (record.status == 0 && record.type == 1) {
          return [
            <a
              key={record.employeeId}
              onClick={() => {
                setCurrentRowDetail(record);
                handleUpdateModalVisible(true);
              }}
            >
              审核
            </a>,
          ];
        }
        return ['-'];
      },
    },
    {
      title: '人员',
      key: 'employeeName',
      dataIndex: 'employeeName',
      fixed: true,
    },
    {
      title: '类型',
      key: 'type',
      width: 80,
      dataIndex: 'type',
      valueType: 'select',
      fixed: true,
      // 1员工挂靠 2企业挂靠 3员工离职 4企业离职
      request: async () => {
        return [
          { value: 1, label: '员工挂靠' },
          { value: 2, label: '企业添加' },
          { value: 3, label: '员工离职' },
          { value: 4, label: '企业解聘' },
        ];
      },
    },
    {
      title: '申请时间',
      key: 'createTime',
      dataIndex: 'createTime',
      valueType: 'dateTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        0: {
          text: '待审核',
          status: 'Default',
        },
        1: {
          text: '通过',
          status: 'Success',
        },
        2: {
          text: '拒绝',
          status: 'Error',
        },
      },
    },
    {
      title: '企业',
      key: 'enterpriseName',
      dataIndex: 'enterpriseName',
    },
    {
      title: '备注',
      key: 'message',
      dataIndex: 'message',
    },
    {
      title: '审核时间',
      key: 'updateTime',
      dataIndex: 'updateTime',
      valueType: 'dateTime',
    },
    {
      title: '审核人',
      key: 'updateBy',
      dataIndex: 'updateBy',
    },
  ];

  const orgPostColumns: ProColumns<OrgPost>[] = [
    {
      title: '部门',
      key: 'orgId',
      dataIndex: 'orgId',
      valueType: 'treeSelect',
      request: requestOrg,
      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: '请选择部门',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
        treeLine: true,
        treeDefaultExpandAll: true,
        fieldNames: { label: 'label', value: 'id', children: 'children' },
      },
    },
    {
      title: '岗位',
      key: 'postId',
      dataIndex: 'postId',
      valueType: 'select',
      request: requestPost,
      fieldProps: {
        dropdownMatchSelectWidth: false,
        placeholder: '请选择岗位',
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
        // fieldNames: {label: 'postName', value: 'postId'},
      },
    },
    {
      title: '管理类型',
      key: 'managerType',
      dataIndex: 'managerType',
      valueType: 'select',
      request: async () => {
        return [
          { value: 10, label: '员工' },
          { value: 11, label: '主管' },
        ];
      },
    },
    {
      title: '是否含下级',
      key: 'hasLeaf',
      dataIndex: 'hasLeaf',
      valueType: 'select',
      request: async () => {
        return [
          { value: 0, label: '不包含' },
          { value: 1, label: '包含' },
        ];
      },
    },
    {
      width: 50,
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => {
        return [];
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<EmployeeListItem>
        headerTitle="从业记录"
        actionRef={actionRef}
        rowKey="employeeId"
        search={{
          labelWidth: 120,
        }}
        request={attachedList}
        columns={columns}
        options={false}
      />
      <Drawer
        width={'80%'}
        visible={createModalVisible}
        onClose={() => {
          setCurrentRow(undefined);
          handleModalVisible(false);
        }}
        destroyOnClose={true}
        title={currentRow?.name && currentRow?.name + '记录详情'}
        extra={
          currentRow &&
          currentRow.workType > 0 && (
            <Popconfirm
              key="delete"
              okButtonProps={{ danger: true }}
              title={`确认解聘员工【${currentRow.name}】?`}
              onConfirm={async () => {
                // setCurrentRow(record);
                await attachedLeaveEmployee(currentRow.employeeId);
                actionRefDetail.current?.reloadAndRest?.();
              }}
              okText="解聘"
              cancelText="取消"
            >
              <Button danger size="small">
                解聘此员工
              </Button>
            </Popconfirm>
          )
        }
      >
        {currentRow?.employeeId && (
          <ProTable<AttachedDetailItem>
            // headerTitle="从业记录"
            actionRef={actionRefDetail}
            rowKey="attachedId"
            scroll={{ x: 2000 }}
            search={false}
            request={attachedDetail}
            columns={detailColumns}
            options={false}
            params={{
              employeeId: currentRow.employeeId,
            }}
          />
        )}
      </Drawer>

      <ModalForm<EmployeeBody>
        title={'员工挂靠审核'}
        // width="600px"
        formRef={formRef}
        visible={updateModalVisible}
        onVisibleChange={(visible) => {
          if (!visible) {
            setCurrentRowDetail(undefined);
          }
          handleUpdateModalVisible(visible);
        }}
        onFinish={saveSubmit}
        request={async (params) => {
          const { data } = await loadEmployee(params);
          if (data?.orgPostList.length == 0) {
            data.orgPostList = [
              {
                id: Date.now(),
                orgId: 0,
                managerType: 10,
                hasLeaf: 0,
              },
            ];
          }
          data.attachedId = currentRowDetail?.attachedId;
          setEditableRowKeys(() => data?.orgPostList.map((item) => item.id));
          return data;
        }}
        params={{ ...currentRow }}
      >
        <ProFormText hidden name="employeeId" />
        <ProFormText hidden name="attachedId" />
        <ProFormText
          rules={[
            {
              required: true,
              message: '手机号',
            },
          ]}
          disabled
          label={'手机号'}
          placeholder={'请输入手机号码'}
          name="mobile"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '员工姓名',
            },
          ]}
          disabled
          label={'员工姓名'}
          placeholder={'请输入员工姓名'}
          name="name"
        />
        <ProFormText
          rules={[
            {
              required: true,
              message: '身份证号',
            },
          ]}
          disabled
          label={'身份证号'}
          placeholder={'请输入身份证号'}
          name="idCard"
        />

        <ProForm.Item label="部门和岗位" name="orgPostList" trigger="onValuesChange">
          <EditableProTable<OrgPost>
            rowKey="id"
            toolBarRender={false}
            columns={orgPostColumns}
            onChange={(value) => {
              console.log(value);
            }}
            controlled={true}
            maxLength={5}
            recordCreatorProps={{
              creatorButtonText: '新增部门',
              newRecordType: 'dataSource',
              record: () => ({
                id: Date.now(),
              }),
            }}
            editable={{
              type: 'multiple',
              editableKeys,
              onChange: setEditableRowKeys,
              actionRender: (row, _, dom) => {
                return [dom.delete];
              },
            }}
          />
        </ProForm.Item>
        <ProFormRadio.Group
          rules={[
            {
              required: true,
              message: '在职类型',
            },
          ]}
          name="workType"
          label="在职类型"
          options={[
            {
              label: '全职',
              value: 1,
            },
            {
              label: '兼职',
              value: 2,
            },
          ]}
        />
        <ProFormSelect
          name="practitionersType"
          label="从业类型"
          request={async () => [
            { label: '普通从业人员', value: 0 },
            { label: '特种从业人员', value: 1 },
            { label: '安全管理员', value: 3 },
            { label: '企业主要负责人', value: 4 },
            { label: '安全管理员+普通从业人员', value: 5 },
            { label: '其它', value: 2 },
          ]}
          rules={[{ required: true }]}
        />
        <ProFormRadio.Group
          rules={[
            {
              required: true,
              message: '请选择审核结果',
            },
          ]}
          name="status"
          label="审核结果"
          options={[
            {
              label: '通过',
              value: 1,
            },
            {
              label: '拒绝',
              value: 2,
            },
          ]}
        />
      </ModalForm>
    </PageContainer>
  );
};

export default AttacList;
